﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Threading;

namespace YanMsg
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {

        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                //当前运行WPF程序的进程实例
                Process process = Process.GetCurrentProcess();
                //遍历WPF程序的同名进程组
                foreach (Process p in Process.GetProcessesByName(process.ProcessName))
                {
                    //不是同一进程并且本进程启动时间最晚,则关闭较早进程
                    if (p.Id != process.Id && (p.StartTime - process.StartTime).TotalMilliseconds <= 0)
                    {
                        p.Kill();//这个地方用kill 而不用Shutdown();的原因是,Shutdown关闭程序在进程管理器里进程的释放有延迟不是马上关闭进程的
                        //Application.Current.Shutdown();
                        return;
                    }
                }
                base.OnStartup(e);
            }
            catch (Exception ex)
            {

                MessageBox.Show("OnStartup"+ex.ToString());
            }
       
        }

        private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            string info ="Application_DispatcherUnhandledException"+ e.Exception.Message;
            MessageBox.Show(info);
            //using (System.IO.StreamWriter sw = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "log.txt"))
            //{
            //    sw.WriteLine(info);
            //}
            e.Handled = true;//如果不加，在捕获异常后程序会退出
        }
    }

}
